using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using TemperatureWP.Model;
using TemperatureWP.Utilities;
using TemperatureWP.Views;

namespace TemperatureWP.ViewModel
{
    public class MainViewModel : ExtendedViewModelBase
    {
        public MainViewModel()
        {
            // Show progressbar
            IsLoading = true;

            // Initialize commands
            OnLoadCommand = new RelayCommand(OnLoad); // Not in use
            UpdateCommand = new RelayCommand(Update);

            // Initialize collections
            TemperatureCollection = new ObservableCollection<TemperatureModel>();
            MeasurementCollection = new ObservableCollection<MeasurementModel>();
            IntervalCollection = InitIntervalModelCollection.Initialize();

            // Initialize datasource
            ReceiveData("http://temperaturerest.cloudapp.net/Sensor/GetListForView", ReceiveSensorData);
            //ReceiveData("http://temperaturerest.cloudapp.net/Measurements/Get/1/0/", ReceiveMeasurements);
        }

        // Receive data asynchronously
        private void ReceiveSensorData(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            TemperatureCollection.Clear();

            var data = JsonConvert.DeserializeObject<ObservableCollection<TemperatureModel>>(e.Result);
            foreach (var item in data)
            {
                if (item != null)
                    TemperatureCollection.Add(item);
            }

            ThisApp.TemperatureCollection = TemperatureCollection;

            // Select first temperature model to be displayed on graf as default
            if (SelectedMeasurement == null)
                SelectedMeasurement = TemperatureCollection.FirstOrDefault();

            // Hide progressbar
            if (IsLoading)
                IsLoading = false;
        }

        private void ReceiveMeasurements(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            var data = JsonConvert.DeserializeObject<ObservableCollection<MeasurementModel>>(e.Result);
            foreach (var item in data)
            {
                if (item != null)
                    MeasurementCollection.Add(item);
            }
        }

        // Collections
        public ObservableCollection<TemperatureModel> TemperatureCollection { get; set; }

        public ObservableCollection<MeasurementModel> MeasurementCollection { get; set; }

        public ObservableCollection<IntervalModel> IntervalCollection { get; set; }

        // Properties and methods
        // Source example on use of relaycommands: http://jesseliberty.com/2011/01/04/wpfs-mvvm-light-toolkit-soup-to-nuts-part-i/
        public RelayCommand OnLoadCommand { get; private set; }
        private void OnLoad()
        {
            // Do stuff
        }

        public RelayCommand UpdateCommand { get; private set; }
        private void Update()
        {
            IsLoading = true;
            ReceiveData("http://temperaturerest.cloudapp.net/Sensor/GetListForView", ReceiveSensorData);
        }

        private TemperatureModel _selectedTemperature;
        public TemperatureModel SelectedTemperature
        {
            get
            {
                return _selectedTemperature;
            }
            set
            {
                if (value == null)
                    return;

                if (ThisApp == null)
                    return;

                _selectedTemperature = value;

                // Set selected temperature model as active temperature model
                ThisApp.ActiveTemperature = _selectedTemperature;

                // Unselected selected item in listbox - not a satisfying solution
                _selectedTemperature = null;
                NotifyPropertyChanged(this, () => SelectedTemperature);

                Navigate(typeof(TargetTemperatureView));
            }
        }

        private VisualBoolean _isLoading;
        public VisualBoolean IsLoading
        {
            get
            {
                return _isLoading;
            }
            set
            {
                _isLoading = value;
                NotifyPropertyChanged(this, () => IsLoading);
            }
        }

        private TemperatureModel _selectedMeasurement;
        public TemperatureModel SelectedMeasurement
        {
            get { return _selectedMeasurement; }
            set
            {
                if (value == null)
                    return;

                _selectedMeasurement = value;

                MeasurementCollection.Clear();
                var interval = _selectedInterval == null ? 0 : _selectedInterval.Interval;
                var uri = string.Format("http://temperaturerest.cloudapp.net/Measurements/Get/{0}/{1}/", _selectedMeasurement.Id, interval);

                ReceiveData(uri, ReceiveMeasurements);
            }
        }

        private IntervalModel _selectedInterval;
        public IntervalModel SelectedInterval
        {
            get { return _selectedInterval; }
            set
            {
                _selectedInterval = value;

                MeasurementCollection.Clear();
                var id = _selectedMeasurement == null ? 1 : _selectedMeasurement.Id;
                var uri = string.Format("http://temperaturerest.cloudapp.net/Measurements/Get/{0}/{1}/", id, _selectedInterval.Interval);

                ReceiveData(uri, ReceiveMeasurements);
            }
        }
    }
}